import React from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { createForm } from 'rc-form';
import cx from 'classnames';
import { WingBlank, WhiteSpace, Flex, List, Button, Toast, TextareaItem } from 'antd-mobile';
import styles from '../scale/styles.less';

function ScaleHypBzfxTemplate({ dispatch, location, form, scalevalue, ...rest }) {

  const { state, query } = location;
  const { getFieldProps, getFieldValue, setFieldsValue, validateFields } = form;

  const { step, ...restState } = state;

  const isNativeApp = location.pathname.indexOf('/scale_hyp') !== -1 && query.s === 'app';

  if (!Object.keys(scalevalue).length) {
    scalevalue = [[], [], [], []];
    dispatch({ type: 'scale/save', payload: { scalevalue } });
  
  }

  function handleNormal({ target: { type, name, value,id } }) {
    let normal = scalevalue[0]; //一般症状
    const main = scalevalue[1]; //主症
    const tp = scalevalue[2]; //舌脉症状
    const canNotSelect = scalevalue[3]; //不可选症状
    if (Array.from(normal).find(item => item.title === value)) {
      if(main.length < 3 ) {
        normal = Array.from(normal).filter(item => item.title !== value);
        // main[main.length] = {}; 之前的写法
        // ScaleHypDetailTemplate中validateFields函数的normal.push({id:values[key],title:key});
        main.push({id:id,title:value});
      }
    }
    dispatch({ type: 'scale/save', payload: { scalevalue: [normal, main, tp, canNotSelect] } });
  }

  function handleMain({ target: { type, name, value, id } }) {
  
    const normal = scalevalue[0]; //一般症状
    let main = scalevalue[1]; //主症
    const tp = scalevalue[2]; //舌脉症状
    const canNotSelect = scalevalue[3]; //不可选症状

    if (Array.from(main).find(item => item.title === value)) {
    
      main = Array.from(main).filter(item => item.title !== value);
      normal.push({id:id,title:value});//
    }

    dispatch({ type: 'scale/save', payload: { scalevalue: [normal, main, tp, canNotSelect] } });
  }
  function isDisable () {
    const main = scalevalue[1];
    if (main.length > 2) {
      return true;
    }
  }

  function submit() {
    const normal = [];
    const main = [];
    const tp = [];

    //遍历一般症状的id,提交的时候提交的是 scalevalue的id
    for (var i = scalevalue[0].length - 1; i >= 0; i--) {
      normal.push(scalevalue[0][i].id);
    }
    for (var i = scalevalue[1].length - 1; i >= 0; i--) {
      main.push(scalevalue[1][i].id);
    }
     for (var i = scalevalue[2].length - 1; i >= 0; i--) {
      tp.push(scalevalue[2][i].id);
    }
    if (main.length < 1 || main.length > 3) {
      Toast.fail('请选择1至3个主症', 1);
    } else {
      Toast.loading('请稍等...');
      Toast.loading('正在加载');
      dispatch({
        type: 'scale/submitQuestions1',
        payload: {
          // type: query.type || state.type,
          type: 'hyp',
          patientId: state.patientid,
          familyId: JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId,
          patientValue1: `${normal.join(';')}`,
          patientValue2: `${main.join(';')}`,
          patientValue3: `${tp.join(';')}`,
          ...rest,
        },
      });
    }
  }

  function bzfxHandler() {

    if (isNativeApp) {
      submit();
    }
  }
  var clickNum=1;
  function submitHandler() {

    if (isNativeApp) {
      dispatch(
        routerRedux.replace({
          pathname: `${location.pathname.replace('/scale_hyp_bzfx', '/scale_hyp_report')}?s=${query.s}&doctorid=${query.doctorid}&memberid=${query.memberid}`,
          state: {
            ...restState,
          },
        }),
      );
    } else {
      if(clickNum){
        Toast.loading('正在加载');
        clickNum= 0;
         submit();
      }
    }
  }
  return (
    <WingBlank size="md">
      <WhiteSpace />
      <List>
        <List.Item>
          <Flex justify="center">辨证分型</Flex>
          <WhiteSpace size="xl" />
          <Flex>一般症状</Flex>
          <WhiteSpace />
          <Flex wrap="wrap" className={styles.questionOptions} key="normal">
            {scalevalue[0].map((item, i) => {
              const key = item.id;
              const value = item.title;
              return (
                <label key={key} className={cx(styles.questionOption, styles.questionOptionNormal,{[styles.questionOptionDisable]: isDisable()})}>
                  <input {...getFieldProps(`${key}`)} type="radio" name={key} value={item.title} id={item.id} onChange={handleNormal} />
                  {value}
                </label>
              );
            })}
          </Flex>
        </List.Item>

        <List.Item>
          <Flex>主诉<span style={{fontSize: "0.2rem"}}>（请在一般症状中选择1~3项较为严重的症状）</span></Flex>
          <WhiteSpace />
          <Flex wrap="wrap" className={styles.questionOptions} key="main">
            {scalevalue[1].map((item, i) => {
              const key = item.id;
              const value = item.title;
              return (
                <label key={key} className={cx(styles.questionOption, styles.questionOptionNormal)}>
                  <input {...getFieldProps(`${key}`)} type="radio" name={key} value={item.title} id={item.id} onChange={handleMain} />
                  {value}
                </label>
              );
            })}
          </Flex>
        </List.Item>
      </List>
      <WhiteSpace />
      <List>
       {/* <List.Item>
                 <Flex>舌脉症状</Flex>
                 <WhiteSpace />
                 <Flex wrap="wrap" className={styles.questionOptions} key="tp">
                   {scalevalue[2].map((item, i) => {
                     const key = item.id;
                     const value = item.title;
                     return (
                       <label key={key} className={cx(styles.questionOption, styles.questionOptionNormal)}>
                         <input {...getFieldProps(`${key}`)} type="radio" name={key} value={item.title} id={item.id} />
                         {value}
                       </label>
                     );
                   })}
                 </Flex>
               </List.Item>*/}
        {isNativeApp
          ? <List.Item>
            <WingBlank>
                <Flex>
                  <Flex.Item>
                    <Button type="primary" onClick={bzfxHandler}>辨证</Button>
                  </Flex.Item>
                </Flex>
                <WhiteSpace size="xl" />
                <Flex>
                  <TextareaItem
                    {...getFieldProps('report', {
                      initialValue: rest.report ? rest.report.Report1 : '',
                    })}
                    title="辨证分型:"
                    editable={false}
                  />
                </Flex>
              </WingBlank>
          </List.Item>
          : null}
      </List>
      <WhiteSpace />
      <List>
        <List.Item>
          <WingBlank>
            <Flex>
              <Flex.Item>
                <Button type="primary" onClick={submitHandler}>提交</Button>
              </Flex.Item>
            </Flex>
          </WingBlank>
        </List.Item>
      </List>
    </WingBlank>
  );
}

export default connect(({ scale }) => ({ ...scale }))(createForm()(ScaleHypBzfxTemplate));
